package com.eco.fanliapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.SqjdAppUserMapper;
import com.eco.fanliapp.dao.SyUserMoneyMapper;
import com.eco.fanliapp.dao.SyUserTaskMapper;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.vo.SyModuleOnOffVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.awt.print.PrinterAbortException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-08-07
 */
@Service
public class SyUserMoneyServiceImpl extends ServiceImpl<SyUserMoneyMapper, SyUserMoney> implements ISyUserMoneyService {

    private static final Logger log = LoggerFactory.getLogger(SyUserMoneyServiceImpl.class);
    @Autowired
    private SyUserMoneyMapper syUserMoneyMapper;

    @Autowired
    private UpdateUserCommon updateUserCommon;

    @Autowired
    private SyUserTaskMapper syUserTaskMapper;
    @Autowired
    private ISySignSetupService iSySignSetupService;
    @Autowired
    private IAppUserService appUserService;


    @Autowired
    private SqjdAppUserMapper sqjdAppUserMapper;
    @Autowired
    private ISyUserMoneyLogService syUserMoneyLogService;

    @Autowired
    private RedisLockService redisLockService;
    @Autowired
    private RedisTemplateService redisTemplateService;

    @Override
    public SyUserMoney selectByUserId(Long userId) {
        QueryWrapper<SyUserMoney> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        return syUserMoneyMapper.selectOne(queryWrapper);
    }

    @Override
    public int insertSyUserMoney(SyUserMoney syUserMoney) {
        return syUserMoneyMapper.insert(syUserMoney);
    }

    @Override
    public int updateSyUserMoney(SyUserMoney syUserMoney) {
        return syUserMoneyMapper.updateById(syUserMoney);
    }

    @Override
    public int updateUserCashBalanceAmount(BigDecimal money, Long userId) {
        return syUserMoneyMapper.updateUserCashBalanceAmount(money, userId);
    }

    @Override
    public int wxPaySuccessUpdate(Long userId, String amount) {
        return syUserMoneyMapper.wxPaySuccessUpdate(userId, amount);
    }

    /**
     * 任务完成，用户加金币 更新用户金币
     *
     * @param gold
     * @param userId
     * @return
     */
    @Override
    public int updateUserGoldBalanceAmount(Integer gold, Long userId) {
        return syUserMoneyMapper.updateUserGoldhBalanceAmount(gold, userId);
    }

    @Override
    public String countGoldBalanceAmount(Integer companyId, Integer flag) {
        return syUserMoneyMapper.countGoldBalanceAmount(companyId, flag);
    }

    @Override
    public String countYesterdayGoldBalanceAmount() {
        return syUserMoneyMapper.countYesterdayGoldBalanceAmount();
    }

    /**
     * 7天连续签到加金币，创建日志
     *
     * @param userId
     * @return
     */
    @Override
    public ServerResponse userSignTaskSuccessUpdateGold(Long userId) {
        HashMap map = new HashMap();
        Integer goldNum = 0;
        Integer signDays = 0;
        BigDecimal exchangeMoney = new BigDecimal("0");
        //redis锁-时间
        long startTimes = System.currentTimeMillis() + 1000 * 120;


        //获取锁
        if (!redisLockService.lock("signTask_" + userId, startTimes + "")) {
            return ServerResponse.createByErrorMessage("网络拥堵，2分钟后再试吧");
        }

        SyUserTask syUserTask = null;
        String redisKeyStrHasSing = "app_sign_setup_obj_" + userId;
        String is_sign = null;
        if (redisTemplateService.hasKey(redisKeyStrHasSing)) {
            is_sign = redisTemplateService.getTByKey(redisKeyStrHasSing, String.class);
        }
        if (is_sign == null || !"1".equals(is_sign)) {
            syUserTask = syUserTaskMapper.selectSignTaskDay(0, userId);
            if (syUserTask != null) {
                is_sign = "1";
                redisTemplateService.set(redisKeyStrHasSing, is_sign, 60 * 5);
            }
        }
        //判断当天是否签到
        try {
            syUserTask = syUserTaskMapper.selectSignTaskDay(0, userId);
        } catch (Exception e) {
            return ServerResponse.createBySuccessCodeMessage(201, "已签到");
        }
        //7天签到金额
        String redisKeyStr = "app_sign_setup_obj";
        SySignSetup sySignSetup = null;
        if (redisTemplateService.hasKey(redisKeyStr)) {
            sySignSetup = redisTemplateService.getTByKey(redisKeyStr, SySignSetup.class);
        }
        if (sySignSetup == null) {
            sySignSetup = iSySignSetupService.getById(1);
            redisTemplateService.set(redisKeyStr, sySignSetup, 60 * 5);
        }

        if (is_sign == null || syUserTask == null) {
            SyUserTask syUserTask_One = null;
            //判断连续签到第几天
            try {
                syUserTask_One = syUserTaskMapper.selectSignTaskDay(1, userId);
            } catch (Exception e) {
                syUserTask_One = null;
            }

            if (syUserTask_One == null) {
                //第一天签到
                signDays = 1;
                goldNum = sySignSetup.getOneDayGoldNum();
            } else if (syUserTask_One.getTaskSignDay() == 7 || syUserTask_One.getTaskSignDay() == 0) {
                //第一天签到
                signDays = 1;
                goldNum = sySignSetup.getOneDayGoldNum();
            } else if (syUserTask_One.getTaskSignDay() == 1) {
                //第 2 天签到
                signDays = 2;
                goldNum = sySignSetup.getTwoDayGoldNum();
            } else if (syUserTask_One.getTaskSignDay() == 2) {
                //第 3 天签到
                signDays = 3;
                goldNum = sySignSetup.getThreeDayGoldNum();
            } else if (syUserTask_One.getTaskSignDay() == 3) {
                //第 4 天签到
                signDays = 4;
                goldNum = sySignSetup.getFourDayGoldNum();
            } else if (syUserTask_One.getTaskSignDay() == 4) {
                //第 5 天签到
                signDays = 5;
                goldNum = sySignSetup.getFiveDayGoldNum();
            } else if (syUserTask_One.getTaskSignDay() == 5) {
                //第 6 天签到
                signDays = 6;
                goldNum = sySignSetup.getSixDayGoldNum();
            } else if (syUserTask_One.getTaskSignDay() == 6) {
                //获取随机数50-100；
                Random random = new Random();
                int i = random.nextInt(6);
                int sevenGoldNum = (i + 5) * 10;
                //第 7 天签到
                signDays = 7;
                goldNum = sevenGoldNum;
            }
            String remark = "签到金币兑换金额到账";
            exchangeMoney = updateUserCommon.updateUserGoldExchangeMoney(userId, 8, goldNum, 2, signDays, remark);
            if (exchangeMoney != null) {
                map.put("title", "连续签到" + signDays + "天");
                map.put("signDays", signDays);
                map.put("exchangeMoney", exchangeMoney.toString());
                map.put("displayTime", ApiEnum.DIS_TIME);//弹窗显示时间2秒(2000毫秒)
                return ServerResponse.createBySuccess("签到成功", map);
            }
        } else {
            return ServerResponse.createBySuccessCodeMessage(201, "已签到");
        }
        return ServerResponse.createByErrorMessage("签到失败");
    }

    /**
     * 现金金额，可兑换金币
     *
     * @return
     */
    @Override
    public ServerResponse getAppTaskMoneyList(Long userId) {
        HashMap map = new HashMap();
        QueryWrapper<SyUserMoney> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        SyUserMoney syUserMoney = syUserMoneyMapper.selectOne(queryWrapper);

        if (syUserMoney != null) {
            BigDecimal cashBalanceAmount = syUserMoney.getCashBalanceAmount();
            Integer goldBalanceAmount = syUserMoney.getGoldBalanceAmount();
            map.put("cashBalance", cashBalanceAmount);
            map.put("goldBalance", goldBalanceAmount);

            return ServerResponse.createBySuccess("可提现金额，已有金币", map);
        } else {
            map.put("cashBalance", 0);
            map.put("goldBalance", 0);

            return ServerResponse.createBySuccess("可提现金额，已有金币", map);
        }
    }

    /**
     * 根据userId创建sy_user_money
     *
     * @param userId
     * @return
     */
    @Override
    public int createUserMoney(Long userId) {
        //首次查询用户钱中是否存在数据
        //redis锁-时间
        long startTimes = System.currentTimeMillis() + 1000 * 3;

        //获取锁
        if (!redisLockService.lock(userId + "createUserMoney", startTimes + "")) {
            log.info("redisLock,新用户创建userMoney，userId{},createTime{}", userId, new Date());
        }
        SyUserMoney oldSyUserMoney = selectByUserId(userId);
        if (oldSyUserMoney == null) {//添加
            SyUserMoney syUserMoney = new SyUserMoney();
            syUserMoney.setUserId(userId);
            syUserMoney.setGoldTotalAmount(0);
            syUserMoney.setGoldBalanceAmount(0);
            syUserMoney.setEnable(1);
            int i = insertSyUserMoney(syUserMoney);
            log.info("新用户创建userMoney，userId{},createTime{}", userId, new Date());
            return i;
        }
        return 0;
    }

    /**
     * 更新省钱间谍数据
     *
     * @param appUser1
     * @param add
     * @param phoneNumber
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSqjd(AppUser appUser1, BigDecimal add, String phoneNumber) throws Exception {

        int i1 = appUserService.updateAppUseraddbalance(appUser1.getUserId(), add);
        int i2 = 0;
        if (i1 > 0) {
            //加过就改为删除状态
            i2 = sqjdAppUserMapper.delByPhoneNum(phoneNumber);
            syUserMoneyLogService.addSyUserMoneyLogNew2(appUser1.getUserId(), appUser1.getBalance(),
                    add, "省钱间谍中存在余额，转入省鸭+" + add, 4);
        }
        if (i2 == 0) {
            //支付失败，手动抛出异常
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚失误
        }
    }

    @Override
    public ServerResponse getGoldNum(Long UserId) {
        Integer userGoldNum = syUserMoneyMapper.getGoldNum(UserId);
        if (userGoldNum == null || userGoldNum == 0) {
            return ServerResponse.createBySuccess("鸭币查询成功", 0);
        }
        return ServerResponse.createBySuccess("鸭币查询成功", userGoldNum);
    }
}
